<?php

namespace App\Common\Utill;

class RsaCypher
{
    /**
     * 功能：公钥加密
     * @param string $data 加密数据
     * @param string $publicKey 公钥
     * @return string
     */
    public static function encryptPublic(string $data, string $publicKey = '')
    {
        try {
            if (empty($publicKey)) {
                throw new  \Exception('私钥不能为空!');
            }
            $res = openssl_public_encrypt($data, $crypted, openssl_pkey_get_public($publicKey));
            if (!$res) {
                throw new \Exception('加密失败,请检查RSA秘钥');
            }
            return base64_encode($crypted);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }


    /**
     * 功能：私钥解密
     * @param string $data 密文token
     * @param string $privateKey 私钥
     * @return string
     */
    public static function decryptPrivate(string $data, string $privateKey = '')
    {
        try {
            if (empty($privateKey)) {
                throw new  \Exception('私钥不能为空!');
            }
            $res = openssl_private_decrypt(base64_decode($data), $decrypted, openssl_pkey_get_private($privateKey));
            if (!$res) {
                throw new \Exception('解密失败,请检查RSA秘钥');
            }
            return $decrypted;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}
